//
//  SelectAreaViewController.m
//  OCUI
//
//  Created by login on 15-7-17.
//
//

#import "SelectAreaViewController.h"
#import "HotCityTableViewCell.h"
#import "CurrentCityTableViewCell.h"
#import <CoreLocation/CoreLocation.h>

@interface SelectAreaViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,HotCityTableViewCellDelegate,CurrentCityTableViewCellDelegate,UIAlertViewDelegate,CLLocationManagerDelegate>
{
    CLLocationManager *myLocationManager;//定位

    UITableView *selectAreaTableView;//显示所有城市的TableView
    NSMutableDictionary *cityDict;//plist文件内容
    NSMutableArray *_suoyin;//右侧索引
    UILabel *charLabel;//索引大写显示
    UIView *whiteView;//搜索栏白色背景
    UISearchBar *search;//搜索
    UIButton *cancelButton;//搜索栏旁边的取消按钮
    UIView *blackView;//黑色半透明遮盖
    
    UITableView *searchTableView;//搜索结果TableView
    NSMutableArray *searchArray;//搜索的总数据
//
}

@property(nonatomic,copy)NSMutableArray *seacherData;//searchTableView的数据源
@end



@implementation SelectAreaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _suoyin = [[NSMutableArray alloc]init];
    searchArray = [[NSMutableArray alloc]init];
    
    self.title = @"请选择城市";
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"消息提示" message:@"请到设置中心去设置开启定位服务" delegate:self cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
        alert.tag=ServicesEnabled;
        [alert show];
    }
    [self initLocationManager];

    [self initDataArray];
    [self initSearchBar];
    [self initUITableView];
}

//初始化CLLocationManager
-(void)initLocationManager
{
    if (myLocationManager) {
        myLocationManager=nil;
        myLocationManager.delegate=nil;
    }
    myLocationManager=[[CLLocationManager alloc]init];
    myLocationManager.desiredAccuracy=kCLLocationAccuracyBest;
    myLocationManager.delegate=self;
    if ([[[UIDevice currentDevice] systemVersion]floatValue]>=8.0) {
        [myLocationManager requestAlwaysAuthorization];
    }
    
}

//初始化数据
- (void)initDataArray
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"citydict" ofType:@"plist"];
    cityDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    
    NSLog(@"%lu",(unsigned long)cityDict.allKeys.count);
    NSLog(@"cityDict---%@",cityDict);
    
    [_suoyin addObject:@"#"];
    
    for (char c='A'; c<='Z'; c++) {
        
        if (c != 'O' && c != 'U' && c != 'V' && c != 'I') {
            [_suoyin addObject:[NSString stringWithFormat:@"%c",c]];
            
        }
    }
    
    for (int i=0; i<cityDict.allKeys.count; i++) {
        [searchArray addObjectsFromArray:cityDict[cityDict.allKeys[i]]];
    }
    
    NSLog(@"searchArray----%@",searchArray);
    
}

//初始化搜索框
- (void)initSearchBar
{
    whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 40)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    search.placeholder = @"请输入城市名称或首字母查询";
    search.delegate = self;
    search.backgroundColor = [UIColor whiteColor];
    [search setTintColor:[UIColor blackColor]];
    search.searchBarStyle = UISearchBarStyleMinimal;
    [whiteView addSubview:search];
    

}

//初始化UITableView
- (void)initUITableView
{
    selectAreaTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 104, self.view.frame.size.width, self.view.frame.size.height - 104)];
    selectAreaTableView.delegate = self;
    selectAreaTableView.dataSource = self;
    selectAreaTableView.tag = 9875;
    [self.view addSubview:selectAreaTableView];

    searchTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStylePlain];
    searchTableView.delegate = self;
    searchTableView.dataSource = self;
    searchTableView.tag = 9876;
    searchTableView.hidden = YES;
    [self.view addSubview:searchTableView];

    
}

#pragma mark - 定位服务

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //检查弹出框的点击按钮是哪一个
    NSLog(@"alertView tag %ld buttonIndex %ld",(long)alertView.tag,(long)buttonIndex);
    AlertTag alertTag=(int)alertView.tag;
    switch (alertTag) {
        case ServicesEnabled: {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            break;
        }
        case RequestLocation: {
            if (buttonIndex!=0) {
                [self initLocationManager];
            }
            break;
        }
        default: {
            break;
        }
    }
    
    
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined: {
            NSLog(@"用户未决定开启定位服务");
            break;
        }
        case kCLAuthorizationStatusDenied: {
            {
                //                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示信息" message:@"如果拒绝将无法使用本软件" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"ok", nil];
                //                alertView.tag=RequestLocation;
                //                [alertView show];
            }
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways: {
            [myLocationManager startUpdatingLocation];
            break;
        }
            
        case kCLAuthorizationStatusAuthorizedWhenInUse: {
            
            break;
        }
        default: {
            break;
        }
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [myLocationManager stopUpdatingLocation];
    NSLog(@"location ok");
    
    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            NSLog(@"%@", [test objectForKey:@"State"]);
            
            [self performSelectorOnMainThread:@selector(updateMain:) withObject:test waitUntilDone:YES];
        }
    }];
    
}
//成功定位并更新视图
- (void)updateMain:(NSDictionary *)dic
{
    //    cityLabel.text = dic[@"State"];
  
    UIButton *button = (UIButton *)[self.view viewWithTag:1234];
    [button setTitle:dic[@"State"] forState:UIControlStateNormal];
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 9875) {
        return _suoyin.count + 1;
    }else
    {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 9875) {
        if (section == 0) {
            return 1;
        }else if(section == 1){
            return 1;
        }else{
            
            NSString *character = _suoyin[section - 1];
            NSArray *areaArray = cityDict[character];
            return areaArray.count;
            
        }

    }else
    {
        return self.seacherData.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 9875) {
        if (indexPath.section == 0) {
            //当前定位城市
            static NSString *cellIdentifier = @"current";
            CurrentCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            cell.delegate = self;
            if (!cell) {
                cell = [[CurrentCityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [cell.currentCity setTitle:@"正在定位" forState:UIControlStateNormal];
            cell.currentCity.tag = 1234;
            
            return cell;
            
        }else if(indexPath.section == 1)
        {
            //热门城市
            NSArray *hotCity = @[@"北京",@"上海",@"广州",@"深圳",@"杭州",@"南京",@"天津",@"武汉",@"重庆"];
            
            static NSString *cellIdentifier = @"cell";
            HotCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            cell.delegate = self;
            if (!cell) {
                cell = [[HotCityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier WithButtonTitle:hotCity];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
        else{
            static NSString *cellIdentifier = @"myCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            
            NSString *character = _suoyin[indexPath.section - 1];
            NSArray *areaArray = cityDict[character];
            
            cell.textLabel.text = areaArray[indexPath.row];
            return cell;
            
        }

    }else if(tableView.tag == 9876)
    {
        //搜索城市
       static NSString *cellID = @"arrayCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        
        cell.textLabel.text = self.seacherData[indexPath.row];
        return cell;
    }else
    {
        return nil;
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 9875) {
        if (section == 0) {
            return @"当前定位城市";
        }else if(section == 1)
        {
            return @"热门城市";
        }else{
            NSString *header = _suoyin[section - 1];
            return header;
        }
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 9875) {
        return 30;
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 9875) {
        if (indexPath.section == 0) {
            return 50;
        }else if(indexPath.section == 1)
        {
            return [HotCityTableViewCell getCellHeight];
        }else{
            return 44;
        }
    }else{
        return 44;
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 9875) {
        if (indexPath.section>=2) {
            
            NSString *character = _suoyin[indexPath.section - 1];
            NSArray *areaArray = cityDict[character];
            
            self.selectCity = areaArray[indexPath.row];
            
            NSLog(@"%@",areaArray[indexPath.row]);
        }

    }if (tableView.tag == 9876) {
        
        NSString *string = self.seacherData[indexPath.row];
        self.selectCity = string;
        NSLog(@"%@",self.selectCity);
    }
}

#pragma mark - 索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView.tag == 9875) {
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            return nil;
        }
        return _suoyin;

    }else
    {
        return nil;
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    [self showBigSelectedCharacter:title];

    
    if ([title isEqual:@"#"]) {
        
        [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        return 0;
        
    }else{
        NSInteger selectSection = 0;
        
        for (int i=0; i<_suoyin.count; i++) {
            
            if ([_suoyin[i] isEqual:title]) {
                selectSection = i;
                break;
            }
            selectSection = 0;
        }
        selectSection += 1;
        
        [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:selectSection] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        return selectSection;

    }
    
}

//点击索引视图中心出现大字母
- (void)showBigSelectedCharacter:(NSString *)title
{
    if (charLabel) {
        [charLabel removeFromSuperview];
    }
    
    charLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    charLabel.center = self.view.center;
    charLabel.backgroundColor = [UIColor yellowColor];
    charLabel.text = title;
    charLabel.textAlignment = NSTextAlignmentCenter;
    charLabel.font = [UIFont boldSystemFontOfSize:35];
    charLabel.textColor = [UIColor blackColor];
    [self.view addSubview:charLabel];
    
    [UIView animateWithDuration:1 animations:^{
        charLabel.alpha = 0;
    }];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self didEndSeacherBarEditing];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    if (searchTableView.hidden == NO) {
        [searchBar becomeFirstResponder];
    }else{
        [self beginSearcherBarEditing];
    }
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0)
{
    return YES;
}

//搜索城市
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchText);
    
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchText];
    self.seacherData = [NSMutableArray arrayWithArray:[searchArray filteredArrayUsingPredicate:preicate]];
    NSLog(@"%@",self.seacherData);
    
    [searchTableView reloadData];
    
    if (searchText.length == 0) {
        [self hideSearchCityView];
    }else
    {
        [self showSearchCityView];
    }
}

- (void)showSearchCityView
{
    selectAreaTableView.hidden = YES;//隐藏原来的tableView
    blackView.hidden = YES;//隐藏黑色遮盖
    searchTableView.hidden = NO;
}

- (void)hideSearchCityView
{
    selectAreaTableView.hidden = NO;//隐藏原来的tableView
    blackView.hidden = NO;//隐藏黑色遮盖
    searchTableView.hidden = YES;

}

#pragma mark - 搜索框动画

- (void)beginSearcherBarEditing
{
    [search becomeFirstResponder];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.navigationController setNavigationBarHidden:YES];
        whiteView.frame = CGRectMake(0, 0, self.view.frame.size.width, 60);
        search.frame = CGRectMake(0, 20, self.view.frame.size.width - 100, 40);
        selectAreaTableView.frame = CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height - 60);
        
        cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 100 + 10, 25, 80, 30)];
        cancelButton.backgroundColor = [UIColor lightGrayColor];
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [cancelButton.layer setCornerRadius:5];
        [cancelButton addTarget:self action:@selector(cancelEditingSearchBar) forControlEvents:UIControlEventTouchUpInside];
        [whiteView addSubview:cancelButton];
        
    } completion:^(BOOL finished) {
        
        blackView = [[UIView alloc]initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height - 60)];
        blackView.backgroundColor = [UIColor blackColor];
        blackView.alpha = 0.5f;
        [self.view addSubview:blackView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelEditingSearchBar)];
        tap.numberOfTapsRequired = 1;
        [blackView addGestureRecognizer:tap];
        
    }];

}


- (void)didEndSeacherBarEditing
{
    [search resignFirstResponder];
    
    [UIView animateWithDuration:0.3 animations:^{
       
        [self.navigationController setNavigationBarHidden:NO];
        whiteView.frame = CGRectMake(0, 64, self.view.frame.size.width, 40);
        search.frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
        selectAreaTableView.frame = CGRectMake(0, 104, self.view.frame.size.width, self.view.frame.size.height - 104);
        
        [cancelButton removeFromSuperview];
        [blackView removeFromSuperview];
        
    } completion:^(BOOL finished) {
        
        
        
    }];
    
}
//点击取消
- (void)cancelEditingSearchBar
{
    if (searchTableView.hidden == NO) {
        searchTableView.hidden = YES;
        selectAreaTableView.hidden = NO;
    }
    
    search.text = @"";
    [self didEndSeacherBarEditing];
}
#pragma mark - HotCityTableViewCellDelegate
- (void)getClickedButtonTitle:(NSString *)buttonTitle
{
    self.selectCity = buttonTitle;

    NSLog(@"%@",buttonTitle);
}

#pragma mark - CurrentCityTableViewCellDelegate
- (void)currentCityButtonTitle:(NSString *)buttonTitle
{
    self.selectCity = buttonTitle;
    
    NSLog(@"%@",buttonTitle);
}

- (void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"%@",self.selectCity);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
